package com.thinkit.cms.directives.directive;

import com.thinkit.cms.api.site.SiteService;
import com.thinkit.core.constant.Channel;
import com.thinkit.directive.components.DirectiveInterceptor;
import com.thinkit.processor.channel.ChannelThreadLocal;
import com.thinkit.utils.utils.Checker;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

@Component
public class GlobalDirective implements DirectiveInterceptor {

    @Autowired
    Configuration configuration;

    @Autowired
    SiteService siteService;

    @Override
    public Configuration injecGlobalVariable(Map<String,Object> params) {
        Map<String,Object> variables = new HashMap<>();
        variables.putAll(domainCode());
        return injeceGlobal(variables);
    }

    @Override
    public Configuration injecShareVariable(Map<String,Object> params) {
        Map<String,Object> variables = new HashMap<>();
        variables.putAll(domainCode());
        if(Checker.BeNotNull(params) && !params.isEmpty()){
            variables.putAll(params);
        }
        return injeceShare(variables);
    }

    private Map<String,Object> domainCode(){
        String siteId = ChannelThreadLocal.get(Channel.SITE_ID).toString();
        Map<String,Object> objectMap = siteService.getDomainCode(false,siteId);
        return objectMap;
    }


    private Configuration injeceShare(Map<String,Object> variables){
        Configuration cloneConf = (Configuration)configuration.clone();
        DefaultObjectWrapper objectWrapper = (DefaultObjectWrapper)configuration.getObjectWrapper();
        try {
            if(Checker.BeNotNull(variables) && !variables.isEmpty()){
                for(Map.Entry<String, Object> entry : variables.entrySet()){
                    cloneConf.setSharedVariable(entry.getKey(),objectWrapper.wrap(entry.getValue()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneConf;
    }

    private Configuration injeceGlobal(Map<String,Object> variables){
        Configuration cloneConf = (Configuration)configuration.clone();
        DefaultObjectWrapper objectWrapper = (DefaultObjectWrapper)configuration.getObjectWrapper();
        try {
            if(Checker.BeNotNull(variables) && !variables.isEmpty()){
                for(Map.Entry<String, Object> entry : variables.entrySet()){
                    cloneConf.setCustomAttribute(entry.getKey(),objectWrapper.wrap(entry.getValue()));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cloneConf;
    }
}
